//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer.Components;

namespace CommunityServer.Controls
{
	/// <summary>
	/// Summary description for SinglePager.
	/// </summary>
	public class SinglePager : WebControl, IPagedControl
	{
		public SinglePager()
		{
            this.CssClass = "CommonSinglePager";
		}

        protected enum QSType
        {
            QuestionMark,
            Amper,
            QueryString,
            NoQueryString
        }

        #region Page Data
        static readonly Regex questionMarkRegex = new Regex(@"(\?p\=\d+)",RegexOptions.Compiled|RegexOptions.IgnoreCase);
        static readonly Regex amperMarkRegex = new Regex(@"(\&p\=\d+)",RegexOptions.Compiled|RegexOptions.IgnoreCase);

        static readonly string queryText = "?p={0}";
        static readonly string ampterText = "&p={0}";

        #endregion

        #region Private Members
        private int _pageNumber = -1, _totalPages = 0;
        private string _previousResourceName ="single_pager_previouspage", _nextResourceName = "single_pager_nextpage", _previousText, _nextText, _messageResourceName = "single_pager_message", _messageText, _seperatorText, _seperatorResourceName = "single_pager_seperator";
        #endregion

        #region Public Properties
        public int PageIndex
        {
            get{return _pageNumber;}
            set{_pageNumber=value;}
        }

        public int TotalPages
        {
            get{return _totalPages;}
            set{_totalPages=value;}
        }

        public int TotalRecords 
        {
            get 
            {
                return Convert.ToInt32(ViewState["TotalRecords"]);
            }
            set 
            {
                ViewState["TotalRecords"] = value;
            }
        }

        public virtual int PageSize 
        {
            get 
            {
                int pageSize = Convert.ToInt32(ViewState["PageSize"]);

                if (pageSize == 0) 
                    return 10;

                return pageSize;
            }
            set 
            {
                ViewState["PageSize"] = value;
            }

        }

        public virtual int CalculateTotalPages() 
        {
            int totalPagesAvailable;

            if (TotalRecords == 0)
                return 0;

            // First calculate the division
            //
            totalPagesAvailable = TotalRecords / PageSize;

            // Now do a mod for any remainder
            //
            if ((TotalRecords % PageSize) > 0)
                totalPagesAvailable++;

            return totalPagesAvailable;

        }


        public string PreviousResourceName
        {
            get{return _previousResourceName;}
            set{_previousResourceName = value;}
        }

        public string NextResourceName
        {
            get{return _nextResourceName;}
            set{_nextResourceName = value;}
        }

        public string PreviousText
        {
            get{return _previousText;}
            set{_previousText = value;}
        }

        public string NextText
        {
            get{return _nextText;}
            set{_nextText = value;}
        }

        public string SeperatorText
        {
            get{return _seperatorText;}
            set{_seperatorText = value;}
        }

        public string SeperatorResourceName
        {
            get{return _seperatorResourceName;}
            set{_seperatorResourceName = value;}
        }


        public string MessageResourceName
        {
            get{return _messageResourceName;}
            set{_messageResourceName = value;}
        }

        public string MessageText
        {
            get{return _messageText;}
            set{_messageText = value;}
        }

        #endregion

        CSContext context = CSContext.Current;

        protected string CalculateNewUrl(QSType qs, int pnum)
        {
            switch(qs)
            {
                case QSType.QuestionMark:
                    return questionMarkRegex.Replace(context.RawUrl,string.Format(queryText,pnum));
                case QSType.Amper:
                    return amperMarkRegex.Replace(context.RawUrl,string.Format(ampterText,pnum));
                case QSType.QueryString:
                    return context.RawUrl + string.Format(ampterText,pnum);
                default:
                    return context.RawUrl + string.Format(queryText,pnum);

            }
        }

        protected QSType CalculateQSType()
        {
            if(questionMarkRegex.IsMatch(context.RawUrl))
            {
                return QSType.QuestionMark;
            }
            else if(amperMarkRegex.IsMatch(context.RawUrl))
            {
                return QSType.Amper;
            }
            else if(context.RawUrl.IndexOf("?") > 0)
            {
                return QSType.QueryString;
            }
            else
            {
                return QSType.NoQueryString;
            }
        }

        private static readonly string linkFormat = "<a href = \"{0}\">{1}</a>";
        protected override void Render(HtmlTextWriter writer)
        {
            if(this.TotalPages == 0)
                TotalPages = this.CalculateTotalPages();

            

            if(this.PageIndex == -1 || this.TotalPages <= 1)
            {
                this.Visible = false;
                return;
            }
            

            QSType qs = CalculateQSType();

            writer.Write("<div class = \"{0}\">", this.CssClass);
            

                if(Globals.IsNullorEmpty(this.MessageText))
                {
                    writer.Write(ResourceManager.GetString(this.MessageResourceName));
                }
                else
                {
                    writer.Write(MessageText);
                }

                writer.Write(" ");

                if(this.PageIndex > 0)
                {
                    string plink = CalculateNewUrl(qs, this.PageIndex);
                    string ptext = null;

                    if(Globals.IsNullorEmpty(this.PreviousText))
                    {
                        ptext = ResourceManager.GetString(this.PreviousResourceName);
                    }
                    else
                    {
                        ptext = this.PreviousText;
                    }

                    writer.Write(linkFormat,plink,ptext);

                }
                

                
                if(this.PageIndex + 1 < this.TotalPages)
                {
                    if(this.PageIndex > 0) //add seperator
                    {
                        string sep = Globals.IsNullorEmpty(this.SeperatorText) ? ResourceManager.GetString(this.SeperatorResourceName) : this.SeperatorText;
                        writer.Write(sep);
                    }

                    string nlink = CalculateNewUrl(qs, this.PageIndex + 2);
                    string ntext = null;

                    if(Globals.IsNullorEmpty(this.NextText))
                    {
                        ntext = ResourceManager.GetString(this.NextResourceName);
                    }
                    else
                    {
                        ntext = this.NextText;
                    }

                    writer.Write(linkFormat,nlink,ntext);
                }

            writer.Write("</div>");
 

        }

	}
}
